#!/usr/bin/env python3
"""
统一的日志配置模块
提供简洁有序的日志输出管理
"""

import logging
import sys
import os
from datetime import datetime
from typing import Optional

class ColoredFormatter(logging.Formatter):
    """彩色日志格式化器"""
    
    # 颜色代码
    COLORS = {
        'DEBUG': '\033[36m',    # 青色
        'INFO': '\033[32m',     # 绿色
        'WARNING': '\033[33m',  # 黄色
        'ERROR': '\033[31m',    # 红色
        'CRITICAL': '\033[35m', # 紫色
        'RESET': '\033[0m'      # 重置
    }
    
    def format(self, record):
        # 添加颜色
        if record.levelname in self.COLORS:
            record.levelname = f"{self.COLORS[record.levelname]}{record.levelname}{self.COLORS['RESET']}"
        
        return super().format(record)

class WebRTCLogger:
    """WebRTC专用日志管理器"""
    
    def __init__(self, name: str = "WebRTC", level: str = "INFO"):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(getattr(logging, level.upper()))
        
        # 清除现有处理器
        for handler in self.logger.handlers[:]:
            self.logger.removeHandler(handler)
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(getattr(logging, level.upper()))
        
        # 设置格式化器
        if os.getenv('NO_COLOR') or not sys.stdout.isatty():
            # 无颜色模式
            formatter = logging.Formatter(
                '%(asctime)s | %(levelname)-8s | %(message)s',
                datefmt='%H:%M:%S'
            )
        else:
            # 彩色模式
            formatter = ColoredFormatter(
                '%(asctime)s | %(levelname)-8s | %(message)s',
                datefmt='%H:%M:%S'
            )
        
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)
        
        # 防止日志传播到根日志器
        self.logger.propagate = False
    
    def debug(self, message: str):
        """调试信息"""
        self.logger.debug(message)
    
    def info(self, message: str):
        """一般信息"""
        self.logger.info(message)
    
    def warning(self, message: str):
        """警告信息"""
        self.logger.warning(message)
    
    def error(self, message: str):
        """错误信息"""
        self.logger.error(message)
    
    def critical(self, message: str):
        """严重错误"""
        self.logger.critical(message)
    
    def success(self, message: str):
        """成功信息（绿色）"""
        self.logger.info(f"✅ {message}")
    
    def failure(self, message: str):
        """失败信息（红色）"""
        self.logger.error(f"❌ {message}")
    
    def progress(self, message: str):
        """进度信息（蓝色）"""
        self.logger.info(f"🔄 {message}")
    
    def connection(self, message: str):
        """连接信息（青色）"""
        self.logger.info(f"🔗 {message}")
    
    def media(self, message: str):
        """媒体信息（紫色）"""
        self.logger.info(f"🎵 {message}")
    
    def stats(self, message: str):
        """统计信息（黄色）"""
        self.logger.info(f"📊 {message}")
    
    def fec(self, message: str):
        """FEC信息（橙色）"""
        self.logger.info(f"🔧 {message}")
    
    def fec_success(self, message: str):
        """FEC成功信息（绿色）"""
        self.logger.info(f"🔧✅ {message}")
    
    def fec_error(self, message: str):
        """FEC错误信息（红色）"""
        self.logger.error(f"🔧❌ {message}")
    
    def fec_config(self, message: str):
        """FEC配置信息（蓝色）"""
        self.logger.info(f"🔧⚙️ {message}")

# 全局日志器实例
logger = WebRTCLogger("WebRTC", "INFO")

def setup_logging(level: str = "INFO", quiet: bool = False):
    """设置日志级别"""
    global logger
    
    if quiet:
        level = "WARNING"
    
    logger = WebRTCLogger("WebRTC", level)
    
    # 设置第三方库的日志级别
    logging.getLogger("aiortc").setLevel(logging.WARNING)
    logging.getLogger("av").setLevel(logging.WARNING)
    logging.getLogger("PIL").setLevel(logging.WARNING)
    logging.getLogger("matplotlib").setLevel(logging.WARNING)
    logging.getLogger("numpy").setLevel(logging.WARNING)
    logging.getLogger("cv2").setLevel(logging.WARNING)
    
    return logger

def get_logger() -> WebRTCLogger:
    """获取日志器实例"""
    return logger

# 便捷函数
def log_debug(message: str, **kwargs):
    """调试信息"""
    if kwargs:
        logger.debug(message.format(**kwargs))
    else:
        logger.debug(message)

def log_info(message: str, **kwargs):
    """一般信息"""
    if kwargs:
        logger.info(message.format(**kwargs))
    else:
        logger.info(message)

def log_warning(message: str, **kwargs):
    """警告信息"""
    if kwargs:
        logger.warning(message.format(**kwargs))
    else:
        logger.warning(message)

def log_error(message: str, **kwargs):
    """错误信息"""
    if kwargs:
        logger.error(message.format(**kwargs))
    else:
        logger.error(message)

def log_success(message: str, **kwargs):
    """成功信息"""
    if kwargs:
        logger.success(message.format(**kwargs))
    else:
        logger.success(message)

def log_failure(message: str, **kwargs):
    """失败信息"""
    if kwargs:
        logger.failure(message.format(**kwargs))
    else:
        logger.failure(message)

def log_progress(message: str, **kwargs):
    """进度信息"""
    if kwargs:
        logger.progress(message.format(**kwargs))
    else:
        logger.progress(message)

def log_connection(message: str, **kwargs):
    """连接信息"""
    if kwargs:
        logger.connection(message.format(**kwargs))
    else:
        logger.connection(message)

def log_media(message: str, **kwargs):
    """媒体信息"""
    if kwargs:
        logger.media(message.format(**kwargs))
    else:
        logger.media(message)

def log_stats(message: str, **kwargs):
    """统计信息"""
    if kwargs:
        logger.stats(message.format(**kwargs))
    else:
        logger.stats(message)

def log_fec(message: str, **kwargs):
    """FEC信息"""
    if kwargs:
        logger.fec(message.format(**kwargs))
    else:
        logger.fec(message)

def log_fec_success(message: str, **kwargs):
    """FEC成功信息"""
    if kwargs:
        logger.fec_success(message.format(**kwargs))
    else:
        logger.fec_success(message)

def log_fec_error(message: str, **kwargs):
    """FEC错误信息"""
    if kwargs:
        logger.fec_error(message.format(**kwargs))
    else:
        logger.fec_error(message)

def log_fec_config(message: str, **kwargs):
    """FEC配置信息"""
    if kwargs:
        logger.fec_config(message.format(**kwargs))
    else:
        logger.fec_config(message)

# 日志级别常量
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
CRITICAL = "CRITICAL"